package com.wenquanpage.android15_contentresourcontexts.helper;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.support.v4.util.ArrayMap;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by wenquan on 16/5/14.
 */
public class ContentResolerHelper {

    private static String uri_raw_contacts = "content://com.android.contacts/raw_contacts";
    private static String uri_phone = "content://com.android.contacts/data/phones";
    private static String uri_data= "content://com.android.contacts/data";
    private static String uri_email = "content://com.android.contacts/data/emails";
    private ContentResolver resolver = null;


    /**
     * 添加数据
     * @param resolver  对象
     * @param display_name :联系人
     * @param phone:手机号
     * @param email:邮箱
     * @return
     */
    public static long insertContact(ContentResolver resolver,String display_name,String phone,String email){
        //步骤一:insert一条空白的数据

        ContentValues values = new ContentValues();
        Uri uri = resolver.insert(Uri.parse(uri_raw_contacts),values);
        long id = ContentUris.parseId(uri);
        //步骤二:insert联系人名字

        values.clear();
        values.put("raw_contact_id",id);
        values.put("data1",display_name);
        values.put("data2",display_name);
        values.put("mimetype","vnd.android.cursor.item/name");
        resolver.insert(Uri.parse(uri_data),values);

        //步骤三:insert联系人电话

        values.clear();
        values.put("raw_contact_id",id);
        values.put("data1",phone);
        values.put("data2","2");
        values.put("mimetype","vnd.android.cursor.item/phone_v2");
        resolver.insert(Uri.parse(uri_data),values);

        //步骤四:插入email

        values.clear();
        values.put("raw_contact_id",id);
        values.put("data1",email);
        values.put("data2","1");
        values.put("mimetype","vnd.android.cursor.item/email_v2");
        Uri uri1 = resolver.insert(Uri.parse(uri_data),values);
        return id;
    }

    /**
     * 删除键值为int类型的id数据
     * @param resolver
     * @param id
     * @return
     */
    public static int deleteContact(ContentResolver resolver,int id){
        int count = resolver.delete(Uri.parse(uri_raw_contacts),"_id=?",new String[]{id+""});
        return count>0?count:0;
    }

    /**
     * 删除满足sql语句的数据
     * @param resolver:ContentResoler对象
     * @param sql:删除数据的sql语句
     * @param args:sql中的?,对应的值
     * @return
     */
    public static boolean deleteContact(ContentResolver resolver,String sql,String[] args){
        int count = resolver.delete(Uri.parse(uri_raw_contacts),sql,args);
        return count>0?true:false;
    }

    /**
     * 更新数据
     * @param resolver:ContentResoler对象
     *      要更新的ContentValuers对象,一般要更新两个表的数据,一个是raw_contacts表,一个是data表
     * @param id raw_contacts表中的键值
     * @param map 中键值 只能是phone,email,display_name
     * @return
     */
    public static boolean updateContact(ContentResolver resolver,String id,Map<String,Object> map){
        String sql = "raw_contact_id=? and ";
        String[] args = new String[map.size()];
        Boolean flag = false;
        int i=0;
        int count = 0;
        ContentValues values_update = new ContentValues();
        for(Map.Entry obj:map.entrySet()){
            if(obj.getKey().equals("display_name")) {
                flag = true;
            }
        }



        if(flag){
            values_update.put("display_name",(String) map.get("display_name"));

            //先更新raw_contacts
            count = resolver.update(Uri.parse(uri_raw_contacts),values_update,"_id=?",new String[]{id});

            values_update.clear();
        }


        for(Map.Entry obj:map.entrySet()){
            values_update.put("data1", (String) obj.getValue());
            if(obj.getKey().equals("phone")){
                values_update.put("data2", "2");
                resolver.update(Uri.parse(uri_data),values_update,sql+"  mimetype_id=5",new String[]{id});
            }else if(obj.getKey().equals("email")){
                values_update.put("data2", "1");
                resolver.update(Uri.parse(uri_data),values_update,sql+"  mimetype_id=1",new String[]{id});
            }

        }

        return count>0?true:false;



    }

    /**
     * 按条件查询,返回一个list<Map>集合
     * @param resolver:对象
     * @param backColumn:返回的列,一般需要定义,否则返回二十几个字段,造成数据库冗余,且返回的字段一般命名为:_id或display_name,因为查询的是raw_contacts表
     * backColumn的值中,必须有_id变量
     * @param sql:sql查询语句
     * @param args:对应的占位符
     * @param sortOrder:排序规则
     * @return
     */

    public static List<Map<String,String>> getContactInfo(ContentResolver resolver,String[] backColumn, String sql,String[] args,String sortOrder){
        List<Map<String,String>> list = new ArrayList<>();

        Cursor cursor = resolver.query(Uri.parse(uri_raw_contacts),backColumn,sql,args,sortOrder);

        while (cursor.moveToNext()){
            Map<String,String> map = new ArrayMap<>();
            for (int i =0;i<backColumn.length;i++){
                map.put(backColumn[i],cursor.getString(i));
            }

                // 获取联系人电话信息
                Cursor cursor_msg = resolver.query(Uri.parse(uri_phone), new String[]{"data1"}, "raw_contact_id=?", new String[]{cursor.getString(cursor.getColumnIndex("_id"))}, null);
                StringBuilder sb_phones = new StringBuilder();
                while (cursor_msg.moveToNext()) {
                    sb_phones.append(cursor_msg.getString(0) + "|");
                }
                map.put("phone", sb_phones.toString());
                list.add(map);
                if (cursor_msg != null) {
                    cursor_msg.close();
                }

            // 获取联系人Email信息
            Cursor cursor_emails = resolver.query(Uri.parse(uri_email),new String[]{"data1"},"raw_contact_id=?",new String[]{cursor.getString(cursor.getColumnIndex("_id"))},null);
            StringBuilder sb_emails = new StringBuilder();
            while(cursor_emails.moveToNext()){
                sb_emails.append(cursor_emails.getString(0)+"|");

            }
            map.put("email",sb_emails.toString());
            if (cursor_emails!=null){
                cursor_emails.close();
            }

            list.add(map);

        }

        return  list;
    }





}
